﻿using Autofac;
using Blm.Utils.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using VisionCloud.Domain.DtoModel.Ms;
using VisionCloud.Domain.Repository.Interface.Ms;
using VisionCloud.Utility;

namespace VisionCloud.Domain.Data
{
    public class DataStore
    {
        public class StoreRule
        {
            /// <summary>
            /// 缓存时间
            /// </summary>
            public const int CachedHours = 1;

            /// <summary>
            /// 标准库
            /// </summary>
            public const string RuleStandards = "Standards";

            /// <summary>
            /// 成员项目
            /// </summary>
            public const string RuleUserProjects = "UserProjects_{userId}";
        }

        public static TimeSpan GetCommonTimeSpan()
        {
            return TimeSpan.FromHours(StoreRule.CachedHours);
        }

        #region 标准库

        private static object standLocker = new object();
        private static List<StandardListModel> standardLists = null;

        /// <summary>
        /// 清除缓存数据，重新从数据库中获取数据
        /// </summary>
        public static void RefreshProjectStandardData()
        {
            standardLists = null;
        }

        /// <summary>
        /// 去除datacache，该对象初始化很慢
        /// </summary>
        /// <returns></returns>
        public static List<StandardListModel> GetStandards(Guid projectGuid)
        {
            if (standardLists == null)
            {
                lock (standLocker)
                {
                    if (standardLists == null)
                    {
                        using (var container = StartupServer.IocContainer.BeginLifetimeScope())
                        {
                            var rep = container.Resolve<IMsProjectStandardRepository>();
                            var list = rep.Where(w => w.ProjectGuid == projectGuid);
                            standardLists = list.Select(w => new StandardListModel()
                            {
                                Code = w.Code,
                                ProjectStandardId = w.ProjectStandardId,
                                Stage = w.Stage,
                                Title = w.Title,
                                Classes = w.Content.ToObject<List<StandardClass>>(),
                                Templates = w.Template.ToObject<List<StandardClass>>()
                            }).OrderBy(x => x.Code).ToList();
                        }
                    }
                }
            }

            return standardLists;
        }

        #endregion 标准库
    }
}